/* 
 * Created on 2007-1-16
 * Last modified on 2007-1-30
 * Powered by YeQiangWei.com
 */
package com.yeqiangwei.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import sun.misc.BASE64Encoder;

import com.yeqiangwei.util.MD5;

public class StringHelper {
	
	private static Logger logger = Logger.getLogger(StringHelper.class.getName());
	
	public static String regexUtils(String original) { 
		StringBuffer buffer = new StringBuffer(original.length()); 
		for (int i=0;i<original.length();i++) { 
			char c=original.charAt(i); 
			if (c=='\\'||c=='$') { 
				buffer.append("\\").append(c); 
			} else{ 
				buffer.append(c); 
			} 
		} 
		return buffer.toString(); 
	} 
	

    public static void main(String args[]){
   	 //String str = "[quote=ccc站在7楼说：][quote=蓝色咖啡坐在板凳上说：]歪了[/quote][/quote]";
   	 //str = com.yeqiangwei.club.view.util.EnCoder.ubbQuote(str);
   	 //System.out.println(str);
    	System.out.println(encodeString("md5of32", "1"));
    }
	  
    /**
     * 正则匹配并完成替换过程
     * @param str 要检索的字符串
     * @param cp 正则匹配条件字符串
     * @param mc 要替换成的字符串
     * @return
     */
    public static String ubbPattern(String str, String cp, String mc, String defaultStr){
        if(Validator.isEmpty(str)){
            return defaultStr;
        }
        try{
        	//str = regexUtils(str);
            Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
            Matcher m = p.matcher(str);
            str = m.replaceAll(mc);
            //System.out.println(str);
        }catch(Exception e){
        	//logger.error(e.toString());
        }
        return str;       
    }
	
	public static List<String> stringToList(String str, String token){
		List<String> list = new ArrayList<String>();
		if(Validator.isEmpty(str)||Validator.isEmpty(token)){
			return null;
		}else{
			if(str.endsWith(token)){
				str = str.substring(0,str.length()-token.length());
			}
			StringTokenizer st = new StringTokenizer(str, token);
			for(int i=0;st.hasMoreTokens();i++){
				list.add(st.nextToken().trim());
			}
			return list;
		}
	}

	public static List<Integer> stringToIntegerList(String str, String token){
		List<Integer> list = new ArrayList<Integer>();
		if(Validator.isEmpty(str)||Validator.isEmpty(token)){
			return null;
		}else{
			if(str.endsWith(token)){
				str = str.substring(0,str.length()-token.length());
			}
			StringTokenizer st = new StringTokenizer(str, token);
			for(int i=0;st.hasMoreTokens();i++){
				list.add(TypeChange.stringToInt(st.nextToken().trim()));
			}
			return list;
		}
	}
	
	public static String[] stringToStrings(String str, String token){
		if(Validator.isEmpty(str)||Validator.isEmpty(token)){
			return null;
		}else{
			if(str.endsWith(token)){
				str = str.substring(0,str.length()-token.length());
			}
			StringTokenizer st = new StringTokenizer(str, token);
			String[] text  = new String[st.countTokens()];
			for(int i=0;st.hasMoreTokens();i++){
				text[i] = (st.nextToken().trim());
			}
			return text;
		}
	}
	
    /**
     * 考虑到中文的字符串长度判断
     * @param str
     * @return
     * com.yeqiangwei.tools
     */
    public static int Glength(String str){
    	if(Validator.isEmpty(str)){
    		return 0;
    	}else{
    		return str.length();
    	}
    }
    /**
     * 
     * @param res
     * @param s
     * @param e
     * @return
     */
    public static String substring(String res, int s, int e, String defaultStr){
    	if(Validator.isEmpty(res)){
    		return defaultStr;
    	}
    	int len = res.length();
    	if(len<s) s = 0;
    	if(s<0) s = 0;
    	if(e<0)e = len;
    	if(e>len)e = len;
    	return res.substring(s,e);
    }
    
    public static String substring(String res, int s, String defaultStr){
    	if(Validator.isEmpty(res)){
    		return defaultStr;
    	}
    	int len = res.length();
    	if(len<s) s = 0;
    	if(s<0) s = 0;
    	return res.substring(s);
    }
    /**
     * 
     * 中英文混和字符串按特定长度截取
     * @param res 中英文混和字符。
     * @param start 截取起始位置。
     * @param length 截取长度。
     * @param charSet 字符编码
     * @return default null
     */
     public static String Gsubstring(String res, int start, int length ,String charSet) {
     	if(Validator.isEmpty(charSet)){
     		charSet = "UTF-8";
     	}
     	if(Validator.isEmpty(res)){
     		return null;
     	}
     	if(res.length()<length){
     		return res;
     	}
     	res = res.trim(); //去掉空格
         if(start<1){
             start=1;
         }
         int i_Start,i_Len ,i,j,ilenByte,i_S,i_L;
         i_Start= 0;
         i_S =0;
         i_Len=0;
         i_L =0;
         try {
             byte[] resBytes = res.getBytes(charSet);
             ilenByte =resBytes.length ;
             for ( i = 0; i < ilenByte; i++) {
                 i_Start = i_Start+1;
                 if (i_Start <=start) {i_S = i_S+1;}
                 
                 if (i_Start >=start){
                     i_Len=i_Len+1; 
                     i_L = i_L +1;
                 } 
                 
                 if (resBytes[i] <0 ) {
                     i = i+2;
                     i_Start = i_Start +1;
                     if (i_Start <start) {i_S = i_S+2;}
                     if (i_Start >=start){
                             i_Len=i_Len+1;
                             i_L=i_L+2;
                     }
                 }
                 if (i_Len >=length) i =ilenByte;
             }
	         byte[] dest = new byte[i_L];
	         for ( j = 0; j < i_L;j++) {
	             dest[j] = resBytes[i_S + j-1];
	         }
	         return new String(dest, charSet);
         } catch (Exception e) {
        	 logger.error(e.toString());
             return null;
         }
     }
     
     
     /**
      * codeType 加密方式， txt加密字符串
      */
     public static String encodeString(String codeType, String txt){
    	 if(codeType==null){
    		 codeType = "md5of16";
    	 }
         if(codeType.equals("md5of16")){
             MD5 m = new MD5();
             return m.getMD5ofStr16(txt);
         }else if(codeType.equals("md5of32")){  
             MD5 m = new MD5();
             return m.getMD5ofStr(txt);
         }else{
             try {
                 MessageDigest gv = MessageDigest.getInstance(codeType);
                 gv.update(txt.getBytes());
                 return new BASE64Encoder().encode(gv.digest());
             }
             catch(java.security.NoSuchAlgorithmException e) {
            	logger.error(e.toString());
             	return null;
             }
         }
     }

     public static String replaces(String src, String fnd, String rep){
         if(Validator.isEmpty(src)){
             return "";
         }
         if(Validator.isEmpty(fnd)){
             return "";
         }
         String dst = src;
         int idx = dst.indexOf(fnd);
         while (idx >= 0){
             dst = dst.substring(0, idx) + rep + dst.substring(idx + fnd.length(), dst.length());
             idx = dst.indexOf(fnd, idx + rep.length());
         }
         return dst;
     }
     
 	/**
 	 * 转换为XML编码
 	 * @param src
 	 * @return
 	 * com.yeqiangwei.tools
 	 */
     public static String xmlEncoder(String src){
         if (Validator.isEmpty(src)){
             return "";
         }
         String xmlencode = src;
         xmlencode = replaces(xmlencode, "&",  "&amp;");
         xmlencode = replaces(xmlencode, "<",  "&lt;");
         xmlencode = replaces(xmlencode, ">",  "&gt;");
         xmlencode = replaces(xmlencode, "\"", "&quot;");
         xmlencode = replaces(xmlencode, "\'", "&acute;");
         return xmlencode;
     }
     
     /**
      * 用于HTML字符串替换
      * @param src
      * @return
      * com.yeqiangwei.tools
      */
     public static String htmlEncoder(String src) {
         if (Validator.isEmpty(src)){
             return "";
         }    
         String htmlencode = new String(src);
         htmlencode = htmlencode.replace("&","&amp;");
         htmlencode = htmlencode.replace("<","&lt;");
         htmlencode = htmlencode.replace(">","&gt;"); 
         htmlencode = htmlencode.replace("\"","&quot;");   
         htmlencode = htmlencode.replace("'","&#039;");
         htmlencode = htmlencode.replace(" ","&nbsp;");       
         htmlencode = htmlencode.replace("\r\n","<br/>");
         htmlencode = htmlencode.replace("\r","<br/>");       
         htmlencode = htmlencode.replace("\n","<br/>");
         return htmlencode;
     }
     
     /**
      * 循环找出匹配内容
      * @param str
      * @param cp
      * @param s 循环匹配内容间隔符
      * @param defaultStr
      * @return
      */
     public static String matcherStr(String str, String cp, String s, String defaultStr)
     {
         String txt = str;
         if(!Validator.isEmpty(str)){
             txt = str;
             Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
             Matcher m = p.matcher(txt);
             StringBuffer sb = new StringBuffer();
             int i=0;
             boolean result = m.find();
             //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
             while(result) {
                 i++;
                 sb.append(m.group());
                 sb.append(s);
                 //继续查找下一个匹配对象
                 result = m.find();
             }
             txt = String.valueOf(sb);
         }else{
             txt = defaultStr;
         }
         return txt;       
     }

     /**
      * 指定第几次匹配才执行替换
      * @param str
      * @param cp
      * @param s
      * @param loop 指定第几次, 0表示循环所有匹配内
      * @param defaultStr 默认内容
      * @return
      */
     public static String matcherStr(String str, String cp, String s, int loop, String defaultStr)
     {
         String txt = str;
         if(Validator.isEmpty(str)){
        	 return defaultStr;
         }
         txt = str;
         Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
         Matcher m = p.matcher(txt);
         StringBuffer sb = new StringBuffer();
         int i=0;
         boolean result = m.find();
         if(!result){
        	 return defaultStr;
         }
         //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
         while(result) {
             i++;
             if(loop==i){
	                sb.append(m.group());
	                sb.append(s);
             }else if(loop==0){
	                sb.append(m.group());
	                sb.append(s);
	                //继续查找下一个匹配对象
	                result = m.find();
             }else{
                 //继续查找下一个匹配对象
                 result = m.find();
             }
         }    
         txt = sb.toString();
         return txt;       
     }
     
     /**
      * 循环找出匹配内容
      * @param str
      * @param cp
      * @return
      */
     public static List<String> matcherList(String str, String cp){
         List<String> list;
         String txt = str;
         if(!Validator.isEmpty(str)){
        	 list = new ArrayList<String>();
             txt = str;
             Pattern p = Pattern.compile(cp,2); //参数2表示大小写不区分
             Matcher m = p.matcher(txt);
             boolean result = m.find();
             //使用循环将句子里所有匹配的内容找出并替换再将内容加到sb里
             while(result) {
                 list.add(m.group());
                 //继续查找下一个匹配对象
                 result = m.find();
             }
         }else{
            list = null;
         }
         return list;       
     }
     
     
     /**
      * 
      * @param txts 字符串
      * @param ii 取指定位置的字符
      * @param t 分割符
      * @param index 默认字符串
      * @return 
      */
     public static String locator(String txts, int ii, String t
    		 , String defaultStr)
     {
    	String str = defaultStr;
    	if(!Validator.isEmpty(txts)){
        	if(txts.substring(0,1).equals(t)){
        		txts = "~" + txts;
        	}
    		txts = txts.replace((t+t),(t+"~"+t));
    		StringTokenizer st = new StringTokenizer(txts, t);
    		String[] txtslist; 
    		int ct = st.countTokens(); //4个元素可以循环四次
    		if(ii>ct){ //判断指定数组长度是否越界
    			str = defaultStr;
    		}else{
	    		txtslist = new String[ct];
	    		for(int i=0;st.hasMoreTokens();i++){
		    		txtslist[i] = (st.nextToken());
		    		if(i==ii){
		    			str = txtslist[ii];
		    		}
	    		}
	    		str = str.replace("~","");
    		}
    	}else{
    		str = defaultStr;
    	}
   		return str;
     }
     
     public static Map<Integer, String> stringToHashMap(String str, String token){
    	 Map<Integer, String> hm = new HashMap<Integer, String>();
    	 if(!Validator.isEmpty(str)){
         	if(str.substring(0,1).equals(token)){
         		str = "~" + str;
        	}
    		StringTokenizer st = new StringTokenizer(str, token);
    		for(int i=0; st.hasMoreTokens(); i++){
    			String s = String.valueOf(st.nextToken());
    			hm.put(i,s.replace("~",""));
    		}
    	 }    	 
    	 return hm;
     }
     
     public static Map<String, String> stringToHashMap(String keys, String values, String token){
    	 Map<String, String> map = new HashMap<String, String>();
    	 if(!Validator.isEmpty(values)&&!Validator.isEmpty(keys)){
    		List<String> value = StringHelper.stringToList(values,token);
    		List<String> key = StringHelper.stringToList(keys,token);
    		for(int i=0; i<key.size(); i++){
    			String k = key.get(i);
    			String v = value.get(i);
    			if(!Validator.isEmpty(k)){
    				map.put(k,v);
    			}
    		}
    	 }    	 
    	 return map;
     }

     
     public static String getString(String str, String start, String last, String defaultStr)
     {
         if (Validator.isEmpty(str)||Validator.isEmpty(start)||Validator.isEmpty(last)){
             return defaultStr;
         }else{
             str = str.replace("\r", "").replace("\n", "");
             int s = 0, l = 0;
             s = str.indexOf(start);
             if (s == -1)
             {
                 return defaultStr;
             }
             String temp = str.substring(s + start.length());
             l = temp.indexOf(last);
             if (l==-1){
                 return defaultStr;
             }
             temp = temp.substring(0, l);
             str = temp;
         }
         return str;
     }
  
     public static String toUTF8(String s){
    	 if(Validator.isEmpty(s)){
    		 return s;
    	 }
         try {
             s = new String(s.getBytes("ISO-8859-1"),"UTF-8");//编码转化
         } catch (UnsupportedEncodingException e) {
            logger.error(s);
         }
    	 return s;
     }
     
     public static String getParameterValuesToStringAndQuote(HttpServletRequest request,String name){
     	StringBuffer sb=new StringBuffer("");
     	String values[]=request.getParameterValues(name);
     	if(values==null)return null;    	    		
     		for(int i=0;i<values.length;i++){
     		sb.append("\'"+values[i].trim()+"\',");
     		}      
     	String str=sb.toString().trim();
     	return "("+str.substring(0, str.length()-1)+")";
     }
     /***
      * 
      * made by XuFeng
      *  2007  下午02:51:25 
      * @param request
      * @param name
      * @return ('asdf','eewa','asdf')
      */
     public static String getParameterToStringAndQuote(HttpServletRequest request,String name){
     	StringBuffer sb=new StringBuffer(" ");
     	String value=request.getParameter(name);
     	if(value.trim().length()==0)return null;
     	String values[]=value.split(",");    	  	    		
     		for(int i=0;i<values.length;i++){
     			sb.append("\'"+values[i].trim()+"\',");
     		}      
     	String str=sb.toString().trim();
     	return "("+str.substring(0, str.length()-1)+")";
     }
   
     
}
